<template>
  <!-- 主容器，包含所有内容 -->
  <view class="recommendation-container" :class="{'from-wardrobe': !showFortuneModules}">
    <!-- 顶部头部区域（状态栏+导航栏） -->
    <view class="header-area" :class="{'from-wardrobe-header': !showFortuneModules}">
      <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
      <view class="nav-header">
        <!-- 返回按钮 -->
        <view class="back-btn" @click="goBack">
          <image class="back-icon" src="https://i.ibb.co/nq8B8z3P/comeback.png" mode="aspectFit"></image>
        </view>
        <!-- 页面标题 -->
        <view class="page-title">{{ showFortuneModules ? '时空衣橱' : '智能搭配' }}</view>
        <view class="placeholder-btn"></view>
      </view>
    </view>

    <!-- 内容区域，动态paddingTop适配头部高度 -->
    <view class="content-area" :style="{ paddingTop: headerHeight }">
      <!-- 推荐商品列表 -->
      <view class="recommendation-list-section">
        <view class="section-header">
          <text class="section-title">搭配单品推荐</text>
          <text class="view-all">查看全部</text>
        </view>
        <view class="recommendation-item" v-for="(item, index) in recommendItems" :key="index">
          <view class="item-image-placeholder">
            <image :src="item.image_url" mode="aspectFit" class="item-image"></image>
          </view>
          <view class="item-details">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-description">{{ item.description }}</text>
            <view class="item-tags">
              <text class="tag recommended" v-if="index === 0">推荐</text>
              <text class="tag hot" v-if="index === 0">热销</text>
              <text class="tag style" v-if="index === 1">合理搭</text>
              <text class="tag new" v-if="index === 1">新品</text>
              <text class="tag luck" v-if="index === 2">开运</text>
              <text class="tag discount" v-if="index === 2">优惠</text>
            </view>
          </view>
          <view class="item-action">
            <text class="item-price">¥{{ item.price || '199' }}</text>
            <button class="add-button" @click="tryOnItem(getItemType(item, index), item.image_url)">一键试穿</button>
          </view>
        </view>
      </view>
      <!-- 试穿预览区 -->
      <view class="preview-section">
        <view class="image-comparison">
          <!-- 左侧：上衣/下衣预览 -->
          <view class="left-column">
            <view class="image-placeholder upper" @click="previewImage(selectedTopImage)" :class="{'animating': isTopAnimating}">
              <image v-if="selectedTopImage" :src="selectedTopImage" mode="aspectFit" class="preview-image"></image>
              <text v-else class="placeholder-text">上衣</text>
              <view class="change-btn" @click.stop="openClothesUploadNotice('top')">
                <text>更换</text>
              </view>
            </view>
            <view class="image-placeholder lower" @click="previewImage(selectedBottomImage)" :class="{'animating': isBottomAnimating}">
              <image v-if="selectedBottomImage" :src="selectedBottomImage" mode="aspectFit" class="preview-image"></image>
              <text v-else class="placeholder-text">下衣</text>
              <view class="change-btn" @click.stop="openClothesUploadNotice('bottom')">
                <text>更换</text>
              </view>
            </view>
          </view>
          <!-- 右侧：模特/生成效果图预览 -->
          <view class="right-column" :class="{'zoom-animation': zoomAnimation}">
            <view class="image-placeholder model-area" @click="previewImage(generatedImage || personImage)" :class="{'generating': isGenerating, 'generated': justGenerated, 'animate-model': shouldAnimateModel && modelImageLoaded}">
              <image v-if="generatedImage" :src="generatedImage" mode="aspectFit" class="preview-image" @error="handleImageError('generated')"></image>
              <image v-else :src="personImage" mode="aspectFit" class="preview-image model-image" @load="onModelImageLoad" @error="handleImageError('model')"></image>
              <view class="change-btn" @click.stop="openUploadNoticeModal">
                <text>更换</text>
              </view>
              <!-- AI生成中遮罩 -->
              <view class="generating-overlay" v-if="isGenerating">
                <view class="scanning-line"></view>
                <view class="generating-spinner"></view>
                <text class="generating-text">AI生成中...</text>
                <view class="progress-container">
                  <view class="progress-bar" :style="{ width: progressValue + '%' }"></view>
                </view>
              </view>
              <!-- 生成成功动画 -->
              <view class="success-animation" v-if="showSuccessAnimation">
                <view class="success-circle"></view>
                <view class="success-checkmark"></view>
                <view class="success-ripple"></view>
                <view v-for="(star, index) in 10" :key="'star-'+index" class="success-star" :style="{transform: `rotate(${index * 36}deg) translateX(${50 + index * 5}px)`,animationDelay: `${index * 0.1}s`}" ></view>
                <view class="success-glow"></view>
              </view>
            </view>
          </view>
        </view>
        <!-- 一键试穿按钮 -->
        <button class="try-on-button" @click="callTryOnAPI" :class="{'button-disabled': loading}">
          <view class="button-content">
            <view class="button-icon" v-if="loading">
              <view class="loading-spinner"></view>
            </view>
            <text>一键试穿</text>
          </view>
        </button>
      </view>
    </view>
    <UploadNoticeModal
      :show="showUploadNotice"
      :localKey="uploadNoticeLocalKey"
      @update:show="showUploadNotice = $event"
      @agree="handleUploadAgree"
      @disagree="handleUploadDisagree"
    />
    <ClothesUploadNoticeModal
      :show="showClothesUploadNotice"
      :localKey="clothesUploadLocalKey"
      @update:show="showClothesUploadNotice = $event"
      @agree="handleClothesUploadAgree"
      @disagree="handleClothesUploadDisagree"
    />
  </view>
</template>

<script>
import Cache from '../../utils/cache';
import { LOGIN_STATUS } from '../../config/cache';
import { getUserInfo } from '../../api/user';
import UploadNoticeModal from '@/components/UploadNoticeModal.vue';
import ClothesUploadNoticeModal from '@/components/ClothesUploadNoticeModal.vue';

export default {
  components: {
    UploadNoticeModal,
    ClothesUploadNoticeModal
  },
  data() {
    return {
      statusBarHeight: 20, // 默认状态栏高度
      navBarHeight: 50, // 导航栏高度
      starCount: 5, // 星星数量
      selectedTopImage: '', // 选中的上衣图片
      selectedBottomImage: '', // 选中的下衣图片
      selectedAccessory: '', // 选中的配饰
      API_BASE_URL: 'https://dashscope.aliyuncs.com/api/v1',
      API_KEY: 'sk-dc4fdd4e5a344a17a0312a9b552b95b8',
      personImage: 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1760598171/p812706.png',
      taskId: '', // 保存任务ID
      generatedImage: '', // 生成的图片URL
      loading: false, // 加载状态
      currentDate: '', // 当前日期
      // 动画状态
      isGenerating: false,
      justGenerated: false,
      showSuccessAnimation: false,
      isTopAnimating: false,
      isBottomAnimating: false,
      zoomAnimation: false, // 添加缩放动画状态
      progressValue: 0, // 进度条值
      progressInterval: null, // 进度条定时器
      uploadServerUrl: '/api/upload/image', // 服务器上传接口地址
      imageUrl: '', // 上传后的图片链接
      
      // 接收传入参数
      modelParams: {
        modelImage: '', // 从上一页接收的模特照片URL
        birthDate: '',
        birthTime: '',
        location: '',
        tripDate: '',
        tripTime: '',
        style: '',
        tags: ''
      },
      
      // 控制运势相关模块的显示
      showFortuneModules: true,
      
      // 打字机动画相关
      luckDescription: new Date().getMonth() + 1 + '月' + new Date().getDate() + '日，五行属水，宜着粉色系，提升异性缘',
      currentLuckText: '',
      luckTextIndex: 0,
      luckTypingTimer: null,
      
      analysisText: '根据您的生辰八字分析，您今日五行缺水，选择粉色系穿搭可以平衡您的命理，增强桃花运势。粉色代表爱情与浪漫，能增加异性缘，柔软线条传达温柔特质。',
      currentAnalysisText: '',
      analysisTextIndex: 0,
      analysisTypingTimer: null,
      
      modelImageLoaded: false, // 模特图片是否已加载
      shouldAnimateModel: true, // 是否应该给模特添加动画
      
      // 试衣记录相关
      recordSaved: false, // 标记是否已保存记录，避免重复保存
      
      // API返回的标签数据
      suitableTags: ['粉色系', '柔软质地', '圆领'], // 适合标签
      notSuitableTags: ['纯黑', '尖锐造型'], // 不适合标签
      
      // 推荐商品列表
      recommendItems: [
        {
          name: "甜美粉色针织衫",
          description: "柔软亲肤面料，提升桃花运势",
          price: "199",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801338.webp",
          item_type: "top"
        },
        {
          name: "高腰百褶半身裙",
          description: "A字型设计，修饰身形，增添甜美感",
          price: "259",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801340.jpeg",
          item_type: "bottom"
        },
        {
          name: "温柔气质V领毛衣",
          description: "精选羊绒面料，V领设计优雅显瘦，凸显颈部线条美",
          price: "129",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801327.jpeg",
          item_type: "top"
        }
      ],
      
      // 添加用户信息字段
      userInfo: {
        token: '',
        avatar: '',
        nickname: '',
        userId: ''
      },
      // 添加新标记
      hasInitializedImages: false,
      showUploadNotice: false,
      showClothesUploadNotice: false,
      clothesUploadType: '', // 'top' 或 'bottom'
      uploadNoticeLocalKey: 'hideUploadNoticeModal_personal_model',
      clothesUploadLocalKey: 'hideClothesUploadNoticeModal_personal_top',
    }
  },
  computed: {
    // 确保返回有效值
    headerHeight() {
      // 使用固定或计算值，避免可能的错误
      const totalHeight = Number(this.statusBarHeight || 20) + Number(this.navBarHeight || 50);
      return totalHeight + 'px';
    }
  },
  onLoad(options) {
    // 获取状态栏高度
    this.getStatusBarHeight();
    
    // 打印用户登录信息，改为从store中获取
    console.log('===== 用户登录信息 =====');
    
    // 直接调用API获取用户信息
    let that = this;
    getUserInfo().then(res => {
      console.log('登录成功，服务器返回的用户信息：', res.data);
      console.log('uid:', res.data.uid);
      console.log('nickname:', res.data.nickname);
      console.log('phone:', res.data.phone);
      
      // 保存到本地存储以便其他页面使用
      uni.setStorageSync('uid', res.data.uid);
      uni.setStorageSync('nickname', res.data.nickname);
      uni.setStorageSync('phone', res.data.phone);
    }).catch(err => {
      console.error('获取用户信息失败:', err);
    });
    
    // 随机生成3-5颗星星
    this.starCount = Math.floor(Math.random() * 3) + 3;
    
    console.log('页面已加载，传入参数:', options);
    
    // 检查是否从衣橱页面进入
    if (options && options.fromWardrobe === 'true') {
      this.showFortuneModules = false;
      console.log('从个人衣橱进入，隐藏运势相关模块');
      
      // 处理从衣橱页面传入的已选衣物
      if (options.selectedTopImage) {
        this.selectedTopImage = options.selectedTopImage;
        console.log('从衣橱页面传入上衣图片:', this.selectedTopImage);
      }
      
      if (options.selectedBottomImage) {
        this.selectedBottomImage = options.selectedBottomImage;
        console.log('从衣橱页面传入下装图片:', this.selectedBottomImage);
      }
    } else if (options && options.showFortuneModules === 'true') {
      this.showFortuneModules = true;
      console.log('从时空衣橱表单页面进入，显示运势相关模块');
    } else {
      this.showFortuneModules = true;
    }
    
    // 初始化文本为空，确保每次进入都有打字效果
    this.currentLuckText = '';
    this.currentAnalysisText = '';
    
    // 解析接收到的参数
    if (options) {
      this.modelParams = {
        modelImage: options.modelImage || '',
        birthDate: options.birthDate || '',
        birthTime: options.birthTime || '',
        location: options.location || '',
        tripDate: options.tripDate || '',
        tripTime: options.tripTime || '',
        style: options.style || '',
        tags: options.tags || ''
      };
      
      console.log('接收到的参数:', this.modelParams);
      
      // 如果有模特图片URL，则设置到personImage
      if (this.modelParams.modelImage) {
        // 确保URL是完整的URL（包含http或https前缀）
        let imageUrl = this.modelParams.modelImage;
        
        // 检查URL是否包含编码字符，尝试解码
        if (imageUrl && imageUrl.includes('%')) {
          try {
            imageUrl = decodeURIComponent(imageUrl);
            console.log('已解码URL:', imageUrl);
          } catch (e) {
            console.error('URL解码失败:', e);
          }
        }
        
        // 确保URL以http开头
        if (imageUrl && imageUrl.indexOf('http') !== 0 && imageUrl.indexOf('//') !== 0) {
          // 尝试使用相对路径或完整路径
          if (getApp().globalData.HTTP_REQUEST_URL) {
            imageUrl = getApp().globalData.HTTP_REQUEST_URL + '/' + imageUrl.replace(/^\/+/, '');
            console.log('已构建完整URL:', imageUrl);
          } else {
            // 如果不是以http或//开头，使用默认图片代替
            console.log('URL格式不正确，使用默认图片');
            imageUrl = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1760598171/p812706.png';
          }
        }
        
        this.personImage = imageUrl;
        console.log('设置模特图片URL:', this.personImage);
        this.shouldAnimateModel = true; // 启用模特动画
      }
      
      // 处理Coze API返回的数据
      if (options.cozeData) {
        try {
          console.log('开始解析cozeData参数');
          // 使用自定义解码方法解码数据
          function customDecode(str) {
            try {
              return decodeURIComponent(
                str
                  .replace(/_p_/g, '%')
                  .replace(/_a_/g, '+')
                  .replace(/_s_/g, '/')
                  .replace(/_e_/g, '=')
              );
            } catch (e) {
              console.error('解码数据时出错:', e);
              return str; // 返回原字符串
            }
          }
          
          const decodedData = customDecode(options.cozeData);
          console.log('解码后的数据长度:', decodedData.length);
          
          // 尝试解析JSON
          try {
            let cozeData;
            
            // 先尝试解析为JSON对象
            try {
              cozeData = JSON.parse(decodedData);
            console.log('解析Coze数据成功');
            } catch (jsonError) {
              console.error('解析JSON数据出错:', jsonError);
              // 如果解析失败，将其作为字符串处理
              cozeData = {
                fortune_analysis: {
                  description: '今日适合简约舒适的穿搭风格，选择柔和色系可以增强个人气场。',
                  suitable: ['舒适', '简约'],
                  not_suitable: ['过于张扬']
                },
                luck_info: {
                  description: new Date().getMonth() + 1 + '月' + new Date().getDate() + '日，宜着舒适百搭装，提升个人气场'
                },
                recommendations: []
              };
              console.log('使用默认Coze数据');
            }
            
            // 检查API数据中是否有choices字段，如果没有则添加空数组
            if (cozeData) {
              console.log('API数据中没有choices字段，添加空数组');
              if (!cozeData.choices) {
                // 确保cozeData是对象类型
                if (typeof cozeData === 'string') {
                  try {
                    cozeData = JSON.parse(cozeData);
                  } catch (e) {
                    cozeData = {};
                  }
                }
                // 添加空的choices数组
                cozeData.choices = [];
              }
            }
            
            // 更新界面显示
            if (cozeData.fortune_analysis && typeof cozeData.fortune_analysis.description === 'string') {
              this.analysisText = cozeData.fortune_analysis.description;
              console.log('命理解析:', this.analysisText.substring(0, 50) + '...');
            } else {
              console.warn('没有找到有效的fortune_analysis.description');
            }
            
            if (cozeData.luck_info && typeof cozeData.luck_info.description === 'string') {
              this.luckDescription = cozeData.luck_info.description;
              console.log('运势描述:', this.luckDescription.substring(0, 50) + '...');
            } else {
              console.warn('没有找到有效的luck_info.description');
            }
            
            // 设置适合标签
            if (cozeData.fortune_analysis && Array.isArray(cozeData.fortune_analysis.suitable)) {
              this.suitableTags = cozeData.fortune_analysis.suitable;
              console.log('适合标签:', this.suitableTags);
            }
            
            // 设置不适合标签
            if (cozeData.fortune_analysis && Array.isArray(cozeData.fortune_analysis.not_suitable)) {
              this.notSuitableTags = cozeData.fortune_analysis.not_suitable;
              console.log('不适合标签:', this.notSuitableTags);
            }
            
            // 处理推荐商品
            if (cozeData.recommendations && Array.isArray(cozeData.recommendations)) {
              // 更新推荐商品列表
              if (cozeData.recommendations.length > 0) {
                this.recommendItems = cozeData.recommendations;
                console.log('设置推荐商品:', JSON.stringify(this.recommendItems));
              } else {
                console.log('API返回的推荐商品列表为空，使用默认推荐');
                this.setDefaultRecommendations();
              }
              console.log('推荐商品数量:', cozeData.recommendations.length);
            } else {
              console.log('API返回数据中没有recommendations字段，使用默认推荐');
              this.setDefaultRecommendations();
            }
            
          } catch (jsonError) {
            console.error('解析JSON数据出错:', jsonError);
            
            // 尝试从字符串中提取JSON
            try {
              const jsonMatch = decodedData.match(/\{(?:[^{}]|(\{(?:[^{}]|{[^{}]*})*\}))*\}/);
              if (jsonMatch) {
                const extractedJson = jsonMatch[0];
                console.log('从文本提取的JSON长度:', extractedJson.length);
                const extractedData = JSON.parse(extractedJson);
                
                // 使用提取的数据更新界面
                if (extractedData.fortune_analysis && extractedData.fortune_analysis.description) {
                  this.analysisText = extractedData.fortune_analysis.description;
                }
                
                if (extractedData.luck_info && extractedData.luck_info.description) {
                  this.luckDescription = extractedData.luck_info.description;
                }
                
                // 处理推荐商品
                if (extractedData.recommendations && Array.isArray(extractedData.recommendations) && extractedData.recommendations.length > 0) {
                  this.recommendItems = extractedData.recommendations;
                  console.log('从提取的JSON中设置推荐商品:', JSON.stringify(this.recommendItems));
                } else {
                  console.log('提取的JSON中没有有效的推荐商品，使用默认推荐');
                  this.setDefaultRecommendations();
                }
              } else {
                console.error('无法从文本中提取JSON');
                this.setDefaultRecommendations();
              }
            } catch (extractError) {
              console.error('从文本提取JSON失败:', extractError);
              this.setDefaultRecommendations();
            }
          }
          
        } catch (e) {
          console.error('处理Coze数据总体出错:', e);
          this.setDefaultRecommendations();
        }
      }
      
      // 修改动画逻辑，不管从哪里进来都有动画效果
      setTimeout(() => {
        this.zoomAnimation = true;
        
        // 1.5秒后开始打字机动画
        setTimeout(() => {
          this.startTypingAnimations();
          
          // 动画完成后恢复正常大小
          setTimeout(() => {
            this.zoomAnimation = false;
          }, 2500);
        }, 1500);
      }, 500);
    } else {
      // 即使没有参数，也应该执行动画
      setTimeout(() => {
        this.zoomAnimation = true;
        
        // 1.5秒后开始打字机动画
        setTimeout(() => {
          this.startTypingAnimations();
          
          // 动画完成后恢复正常大小
          setTimeout(() => {
            this.zoomAnimation = false;
          }, 2500);
        }, 1500);
      }, 500);
    }
    
    // 新增：从本地存储获取衣橱数据并随机选取上衣和裙裤
    try {
      const wardrobeData = uni.getStorageSync('wardrobe_clothes');
      if (wardrobeData) {
        const clothes = JSON.parse(wardrobeData);
        // 随机选上衣
        const tops = clothes.filter(item => item.category === '上衣');
        if (tops.length > 0) {
          const randomTop = tops[Math.floor(Math.random() * tops.length)];
          this.selectedTopImage = randomTop.image;
        } else {
          this.selectedTopImage = '';
        }
        // 随机选裙裤
        const pantsSkirts = clothes.filter(item => item.category === '裙裤');
        if (pantsSkirts.length > 0) {
          const randomBottom = pantsSkirts[Math.floor(Math.random() * pantsSkirts.length)];
          this.selectedBottomImage = randomBottom.image;
        } else {
          this.selectedBottomImage = '';
        }
      }
    } catch (e) {
      console.error('获取衣橱数据失败', e);
      this.selectedTopImage = '';
      this.selectedBottomImage = '';
    }
  },
  onReady() {
    // 这个函数留空，移除所有内部调用
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      try {
        const res = uni.getSystemInfoSync();
        // 只获取状态栏高度，避免其他复杂操作
        this.statusBarHeight = res.statusBarHeight || 20;
        console.log('状态栏高度：', this.statusBarHeight);
      } catch (e) {
        console.error('获取系统信息失败', e);
        // 出错时使用默认值
        this.statusBarHeight = 20;
      }
    },
    
    // 设置默认的运势数据
    setDefaultFortuneData() {
      console.log('设置默认运势数据');
      // 默认运势描述
      this.luckDescription = new Date().getMonth() + 1 + '月' + new Date().getDate() + '日，宜着舒适百搭装，提升个人气场';
      
      // 默认命理分析
      this.analysisText = '今日适合简约舒适的穿搭风格，选择柔和色系可以增强个人气场，展现自信魅力。建议避免过于张扬的色彩和款式。';
      
      // 默认适合和不适合标签
      this.suitableTags = ['舒适', '简约', '百搭'];
      this.notSuitableTags = ['过于张扬', '尖锐造型'];
    },
    
    // 设置默认的推荐商品数据
    setDefaultRecommendations() {
      console.log('设置默认推荐商品');
      // 保留当前的推荐商品
      if (this.recommendItems && this.recommendItems.length > 0) {
        console.log('已有推荐商品，不进行默认设置');
        return;
      }
      
      // 设置默认的推荐商品
      this.recommendItems = [
        {
          name: "甜美粉色针织衫",
          description: "柔软亲肤面料，提升桃花运势",
          price: "199",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801338.webp",
          item_type: "top"
        },
        {
          name: "高腰百褶半身裙",
          description: "A字型设计，修饰身形，增添甜美感",
          price: "259",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801340.jpeg",
          item_type: "bottom"
        },
        {
          name: "温柔气质V领毛衣",
          description: "精选羊绒面料，V领设计优雅显瘦，凸显颈部线条美",
          price: "129",
          image_url: "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801327.jpeg",
          item_type: "top"
        }
      ];
    },
    
    // 返回上一页
    goBack() {
      uni.switchTab({
        url: '/pages/AI_try_on/personal_wardrobe'
      });
    },
    // 处理试穿功能
    tryOnItem(type, imageUrl) {
      console.log('试穿商品:', type, imageUrl);
      
      // 检查是否已有生成图片，如果有则提示需要重新生成
      const hasGeneratedImage = this.generatedImage ? true : false;
      
      // 根据类型设置不同部位的图片并添加动画效果
      if (type === 'top') {
        this.isTopAnimating = true;
        this.selectedTopImage = imageUrl;
        setTimeout(() => {
          this.isTopAnimating = false;
        }, 1500); // 延长动画时间
      } else if (type === 'bottom') {
        this.isBottomAnimating = true;
        this.selectedBottomImage = imageUrl;
        setTimeout(() => {
          this.isBottomAnimating = false;
        }, 1500); // 延长动画时间
      } else if (type === 'accessory') {
        this.selectedAccessory = imageUrl;
        // 可以在这里添加配饰的展示逻辑
      }
      
      // 显示成功提示
      uni.showToast({
        title: '已添加到试衣区',
        icon: 'success',
        duration: 1500
      });
      
      // 如果已有效果图，需要清除并提示用户重新生成
      if (hasGeneratedImage) {
        this.generatedImage = ''; // 清除已生成的效果图
        this.showSuccessAnimation = false; // 关闭成功动画
        this.justGenerated = false; // 重置生成状态
        
        // 稍后提示用户需要重新试穿
        setTimeout(() => {
          uni.showToast({
            title: '请重新点击"一键试穿"',
            icon: 'none',
            duration: 2000
          });
        }, 1600);
      }
      
      // 滚动到页面顶部的试衣区
      this.scrollToTop();
    },
    
    // 调用阿里云试衣API
    callTryOnAPI() {
      if (!this.selectedTopImage && !this.selectedBottomImage) {
        uni.showToast({
          title: '请先选择衣服',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      if (this.loading) return; // 防止重复点击
      
      this.loading = true;
      
      // 先添加缩放动画效果
      this.zoomAnimation = true;
      this.scrollToTop(); // 滚动到顶部
      
      // 延迟一点启动生成动画，让缩放动画先执行
      setTimeout(() => {
        this.isGenerating = true; // 开始生成动画
        // 启动进度条动画
        this.startProgressAnimation();
        
        console.log('===== 试衣API请求开始 =====');
        console.log('请求参数:');
        console.log('- 上衣图片:', this.selectedTopImage || '无');
        console.log('- 下衣图片:', this.selectedBottomImage || '无');
        console.log('- 模特图片:', this.personImage);
        
        // 构建请求参数
        const requestData = {
          model: "aitryon",
          input: {
            person_image_url: this.personImage
          },
          parameters: {
            resolution: -1,
            restore_face: true
          }
        };
        
        // 添加上衣和下衣参数
        if (this.selectedTopImage) {
          requestData.input.top_garment_url = this.selectedTopImage;
        }
        
        if (this.selectedBottomImage) {
          requestData.input.bottom_garment_url = this.selectedBottomImage;
        }
        
        console.log('完整请求数据:', JSON.stringify(requestData, null, 2));
        console.log('API Key:', this.API_KEY.substring(0, 5) + '****');
        console.log('API URL:', this.API_BASE_URL);
        
        // 发起API请求
        uni.request({
          url: `${this.API_BASE_URL}/services/aigc/image2image/image-synthesis/`,
          method: 'POST',
          header: {
            'X-DashScope-Async': 'enable',
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          },
          data: requestData,
          success: (res) => {
            console.log('===== 试衣API提交响应 =====');
            console.log('状态码:', res.statusCode);
            console.log('响应头:', JSON.stringify(res.header, null, 2));
            console.log('响应数据:', JSON.stringify(res.data, null, 2));
            
            if (res.data && res.data.output && res.data.output.task_id) {
              this.taskId = res.data.output.task_id;
              console.log('获取到任务ID:', this.taskId);
              // 轮询查询任务状态
              this.checkTaskStatus();
            } else {
              this.isGenerating = false;
              this.loading = false;
              console.error('提交任务失败, 没有获取到任务ID');
              uni.showToast({
                title: '提交任务失败',
                icon: 'none',
                duration: 2000
              });
            }
          },
          fail: (err) => {
            console.error('===== 试衣API调用失败 =====');
            console.error('错误详情:', JSON.stringify(err, null, 2));
            this.isGenerating = false;
            this.loading = false;
            uni.showToast({
              title: '网络请求失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
      }, 800);
    },
    
    // 查询任务状态
    checkTaskStatus() {
      if (!this.taskId) return;
      
      console.log('===== 查询任务状态 =====');
      console.log('任务ID:', this.taskId);
      
      uni.request({
        url: `${this.API_BASE_URL}/tasks/${this.taskId}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${this.API_KEY}`
        },
        success: (res) => {
          console.log('任务状态查询结果:', JSON.stringify(res.data, null, 2));
          
          if (res.data && res.data.output) {
            const status = res.data.output.task_status;
            console.log('任务状态:', status);
            
            if (status === 'SUCCEEDED') {
              // 任务成功
              console.log('任务成功完成，获取到图片URL:', res.data.output.image_url);
              this.completeProgress(); // 完成进度条
              this.loading = false;
              if (res.data.output.image_url) {
                this.generatedImage = res.data.output.image_url;
                
                // 显示成功动画
                setTimeout(() => {
                  this.isGenerating = false;
                  this.justGenerated = true;
                  this.showSuccessAnimation = true;
                  this.zoomAnimation = false; // 重置缩放状态
                  
                  // 保存试衣记录
                  this.saveTryOnRecord(res.data.output.image_url);
                
                  // 移除不存在的音效播放代码
                  /* 
                  try {
                    const innerAudioContext = uni.createInnerAudioContext();
                    innerAudioContext.src = '/static/sounds/success_wa.mp3'; // 添加成功音效
                    innerAudioContext.play();
                  } catch (e) {
                    console.error('播放音效失败:', e);
                  }
                  */
                }, 500); // 短暂延迟让进度条完成动画
              }
            } else if (status === 'FAILED') {
              // 清除进度条
              console.error('任务失败:', res.data.output.message || '未知错误');
              this.completeProgress();
              this.isGenerating = false;
              this.loading = false;
              uni.showToast({
                title: '试衣失败: ' + (res.data.output.message || '未知错误'),
                icon: 'none',
                duration: 3000
              });
            } else if (status === 'PENDING' || status === 'RUNNING') {
              // 任务仍在进行中，继续轮询
              console.log('任务仍在处理中，2秒后再次查询...');
              setTimeout(() => {
                this.checkTaskStatus();
              }, 2000); // 2秒后再次查询
            }
          } else {
            console.error('查询任务状态失败，响应数据格式不正确:', res.data);
            this.isGenerating = false;
            this.loading = false;
            uni.showToast({
              title: '查询任务状态失败',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          console.error('查询任务状态网络请求失败:', JSON.stringify(err, null, 2));
          this.isGenerating = false;
          this.loading = false;
          uni.showToast({
            title: '网络请求失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    
    // 滚动到页面顶部
    scrollToTop() {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      });
    },
    
    // 预览图片
    previewImage(url) {
      if (!url) return;
      uni.previewImage({
        urls: [url],
        current: url,
        indicator: 'number',
        loop: false
      });
    },
    
    // 更换图片
    changeImage(type) {
      let that = this;
      that.$util.uploadImageChange('upload/image', (res) => {
        // 确保返回URL格式正确
        let imageUrl = res.data.url;
        
        // 检查URL是否以http开头
        if (imageUrl && imageUrl.indexOf('http') !== 0 && imageUrl.indexOf('//') !== 0) {
          // 直接使用完整URL
          imageUrl = getApp().globalData.HTTP_REQUEST_URL + '/' + imageUrl.replace(/^\/+/, '');
          console.log('完整上传URL:', imageUrl);
        }
        
        // 根据类型设置对应的图片并添加动画
        switch(type) {
          case 'top':
            that.isTopAnimating = true;
            that.selectedTopImage = imageUrl;
            setTimeout(() => {
              that.isTopAnimating = false;
            }, 1000);
            break;
          case 'bottom':
            that.isBottomAnimating = true;
            that.selectedBottomImage = imageUrl;
            setTimeout(() => {
              that.isBottomAnimating = false;
            }, 1000);
            break;
          case 'model':
            // 保存到本地存储，以便恢复
            try {
              uni.setStorageSync('ai_try_on_model', imageUrl);
            } catch (e) {
              console.error('保存模特图片到本地存储失败:', e);
            }
            that.personImage = imageUrl;
            
            // 重要修复：如果已经生成了效果图，切换模特时需要清除它
            if (that.generatedImage) {
              that.generatedImage = ''; // 清除已生成的效果图
              that.showSuccessAnimation = false; // 关闭成功动画
              that.justGenerated = false; // 重置生成状态
              
              // 显示切换提示
              uni.showToast({
                title: '已更换模特，请重新试穿',
                icon: 'none',
                duration: 2000
              });
            }
            break;
        }
        
        uni.showToast({
          title: '更换成功',
          icon: 'success'
        });
      }, (err) => {
        console.error('上传图片失败:', err);
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }, (size) => {
        // 图片尺寸回调
        console.log('图片尺寸:', size.w, size.h);
      });
    },
    
    // 开始进度条动画
    startProgressAnimation() {
      this.progressValue = 0;
      // 清除可能存在的旧定时器
      if (this.progressInterval) {
        clearInterval(this.progressInterval);
      }
      
      // 创建新的进度条动画
      this.progressInterval = setInterval(() => {
        // 进度条前进速度非线性，开始快，接近100%时变慢
        if (this.progressValue < 85) {
          this.progressValue += Math.random() * 2 + 1;
        } else if (this.progressValue < 95) {
          this.progressValue += Math.random() * 0.5 + 0.1;
        } else if (this.progressValue < 99) {
          this.progressValue += 0.05;
        }
        
        // 限制最大值为99%，等待实际完成
        if (this.progressValue > 99) {
          this.progressValue = 99;
        }
      }, 200);
    },
    
    // 完成进度条
    completeProgress() {
      // 清除定时器
      if (this.progressInterval) {
        clearInterval(this.progressInterval);
        this.progressInterval = null;
      }
      
      // 设置为100%
      this.progressValue = 100;
    },
    
    // 开始所有打字机动画
    startTypingAnimations() {
      // 如果不显示运势模块，则不启动打字机动画
      if (!this.showFortuneModules) return;
      
      // 清除可能存在的旧定时器
      if (this.luckTypingTimer) clearInterval(this.luckTypingTimer);
      if (this.analysisTypingTimer) clearInterval(this.analysisTypingTimer);
      
      // 开始桃花运势文字动画
      this.startLuckTextTyping();
      
      // 延迟1秒开始命理穿搭分析动画
      setTimeout(() => {
        this.startAnalysisTextTyping();
      }, 1000);
    },
    
    // 桃花运势文字打字机动画
    startLuckTextTyping() {
      this.currentLuckText = '';
      this.luckTextIndex = 0;
      
      this.luckTypingTimer = setInterval(() => {
        if (this.luckTextIndex < this.luckDescription.length) {
          this.currentLuckText += this.luckDescription.charAt(this.luckTextIndex);
          this.luckTextIndex++;
        } else {
          clearInterval(this.luckTypingTimer);
        }
      }, 50); // 每50毫秒打一个字
    },
    
    // 命理穿搭分析打字机动画
    startAnalysisTextTyping() {
      this.currentAnalysisText = '';
      this.analysisTextIndex = 0;
      
      this.analysisTypingTimer = setInterval(() => {
        if (this.analysisTextIndex < this.analysisText.length) {
          this.currentAnalysisText += this.analysisText.charAt(this.analysisTextIndex);
          this.analysisTextIndex++;
        } else {
          clearInterval(this.analysisTypingTimer);
        }
      }, 30); // 每30毫秒打一个字
    },
    
    // 图片加载错误处理
    handleImageError(type) {
      console.error(`图片加载失败: ${type}`, (type === 'model' ? this.personImage : (type === 'generated' ? this.generatedImage : '')));
      
      // 根据类型设置默认图片
      if (type === 'model') {
        // 检查URL是否是编码过的格式，如果是则尝试解码
        if (this.personImage && this.personImage.includes('%')) {
          try {
            // 尝试解码URL
            const decodedUrl = decodeURIComponent(this.personImage);
            console.log('尝试解码URL:', decodedUrl);
            
            if (decodedUrl !== this.personImage) {
              this.personImage = decodedUrl;
              return; // 尝试使用解码后的URL
            }
          } catch (e) {
            console.error('URL解码失败:', e);
          }
        }
        
        // 如果URL解码失败或不需要解码，使用本地默认图片
        // 使用绝对路径，确保在微信小程序中可以访问
        this.personImage = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1760598171/p812706.png';
        console.log('已切换到默认模特图片');
      } else if (type === 'top') {
        this.selectedTopImage = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801338.webp';
      } else if (type === 'bottom') {
        this.selectedBottomImage = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1389646171/p801340.jpeg';
      } else if (type === 'generated') {
        // 如果生成的图片加载失败，清空URL，显示原始模特图片
        console.log('生成图片加载失败，清除生成图片并显示原始模特');
        this.generatedImage = '';
        this.showSuccessAnimation = false;
        this.justGenerated = false;
        this.isGenerating = false;
        
        // 确保模特图片有效
        if (!this.personImage) {
          this.personImage = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1760598171/p812706.png';
        }
        
        uni.showToast({
          title: '图片生成失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    // 处理模特图片加载完成事件
    onModelImageLoad() {
      this.modelImageLoaded = true;
      console.log('模特图片加载完成');
    },
    
    // 保存试衣记录
    saveTryOnRecord(imageUrl) {
      // 避免重复保存
      if (this.recordSaved) return;
      
      console.log('准备保存试衣记录...');
      console.log('生成图片URL:', imageUrl);
      console.log('上衣图片URL:', this.selectedTopImage);
      
      // 打印当前用户信息
      console.log('当前用户信息:');
      console.log('uid:', uni.getStorageSync('uid'));
      console.log('nickname:', uni.getStorageSync('nickname'));
      console.log('phone:', uni.getStorageSync('phone'));
      console.log('token:', uni.getStorageSync('token'));
      
      
      const randomUid = uni.getStorageSync('uid');
      
      // 确保图片URL是有效的
      const validImageUrl = this.ensureValidUrl(imageUrl);
      const validClothesUrl = this.ensureValidUrl(this.selectedTopImage);
      
      console.log('处理后的生成图片URL:', validImageUrl);
      console.log('处理后的上衣图片URL:', validClothesUrl);
      
      // 根据图片中的格式构建记录数据
      const recordData = {
        uid: randomUid, 
        nickname: uni.getStorageSync('nickname') || '',
        phone: uni.getStorageSync('phone') || '',
        title: this.modelParams.style ? `${this.modelParams.style}穿搭` : '今日穿搭',
        icon: '/icons/default.png',
        image_url: validImageUrl, // 修改字段名称与API匹配
        des: this.analysisText || '我的试衣记录',
        suitable: this.suitableTags.join('、'),
        not_suitable: this.notSuitableTags.join('、'),
        clothes_url: validClothesUrl
      };
      
      console.log('试衣记录数据:', JSON.stringify(recordData, null, 2));

      // 使用项目实际的API域名
      const apiBaseUrl = 'https://test.zysemtime.com';
      
      // 获取全局配置的URL，如果为空则使用硬编码值
      const globalBaseUrl = getApp().globalData.HTTP_REQUEST_URL;
      console.log('全局配置的基础URL:', globalBaseUrl);
      
      // 如果全局URL存在，则使用全局URL，否则使用硬编码的URL
      const fullApiUrl = globalBaseUrl ? (globalBaseUrl + '/api/dress_history/add') : (apiBaseUrl + '/api/dress_history/add');
      console.log('使用的完整API URL:', fullApiUrl);
      
      uni.request({
        url: fullApiUrl,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': uni.getStorageSync('token') // 添加授权头，确保API能识别用户
        },
        data: recordData,
        success: (res) => {
          console.log('保存试衣记录响应:', JSON.stringify(res.data, null, 2));
          
          // 处理响应结果，根据图片中的格式调整
          if (res.data && res.data.code === 200) {
            this.recordSaved = true;
            
            // 设置全局标记，告诉history页面需要刷新数据
            getApp().globalData.needRefreshHistory = true;
            console.log('已设置全局刷新标记：needRefreshHistory = true');
            
            uni.showToast({
              title: '已保存至试衣记录',
              icon: 'success',
              duration: 2000
            });
          } else {
            console.error('保存试衣记录失败, 错误详情:', JSON.stringify(res.data, null, 2));
            uni.showToast({
              title: res.data?.message || '保存记录失败',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          console.error('保存试衣记录请求失败:', err);
          console.error('错误详情:', JSON.stringify(err, null, 2));
          
          uni.showToast({
            title: '网络请求失败，请稍后再试',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    
    // 确保URL有效
    ensureValidUrl(url) {
      if (!url) return '';
      
      console.log('处理URL:', url);
      
      // 如果URL已经是完整URL，直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      
      // 如果URL是相对路径，添加基础URL
      const baseUrl = getApp().globalData.HTTP_REQUEST_URL || 'https://test.zysemtime.com';
      const formattedUrl = url.startsWith('/') ? url.substring(1) : url;
      return `${baseUrl}/${formattedUrl}`;
    },
    
    // 根据风格类型获取对应的图标
    getStyleIcon(style) {
      const iconMap = {
        '休闲': '👕',
        '商务': '👔',
        '运动': '🏃',
        '约会': '❤️',
        '见家长': '👨‍👩‍👧',
        '旅行': '✈️'
      };
      return iconMap[style] || '👔';
    },
    
    // 获取商品类型，用于试穿功能
    getItemType(item, index) {
      // 如果商品本身有类型信息，则使用它
      if (item.item_type) {
        return item.item_type;
      }
      
      // 根据商品名称判断类型
      const name = item.name || '';
      if (name.includes('裙') || name.includes('裤') || name.includes('下装')) {
        return 'bottom';
      }
      
      // 根据索引决定默认类型（奇数为下装，偶数为上装）
      return index % 2 === 1 ? 'bottom' : 'top';
    },
    handleUploadAgree(checked) {
      this.showUploadNotice = false;
      this.changeImage('model');
    },
    handleUploadDisagree() {
      this.showUploadNotice = false;
    },
    openUploadNoticeModal() {
      const localKey = 'hideUploadNoticeModal_personal_model';
      if (uni.getStorageSync(localKey)) {
        this.handleUploadAgree(true);
        return;
      }
      this.uploadNoticeLocalKey = localKey;
      this.showUploadNotice = true;
    },
    openClothesUploadNotice(type) {
      const localKey = type === 'top' ? 'hideClothesUploadNoticeModal_personal_top' : 'hideClothesUploadNoticeModal_personal_bottom';
      if (uni.getStorageSync(localKey)) {
        this.handleClothesUploadAgree(true);
        return;
      }
      this.clothesUploadLocalKey = localKey;
      this.clothesUploadType = type;
      this.showClothesUploadNotice = true;
    },
    handleClothesUploadAgree(checked) {
      this.showClothesUploadNotice = false;
      // 弹窗同意后，继续原有的上传逻辑
      this.changeImage(this.clothesUploadType);
    },
    handleClothesUploadDisagree() {
      this.showClothesUploadNotice = false;
    },
  },
  
  // 添加onShow生命周期函数，从本地存储中获取参数
  onShow() {
    console.log('recommendation页面显示');
    
    // 只有在第一次进入页面且没有图片时才从本地存储获取
    if (!this.hasInitializedImages && !this.selectedTopImage && !this.selectedBottomImage) {
      try {
        const wardrobeData = uni.getStorageSync('wardrobe_clothes');
        if (wardrobeData) {
          const clothes = JSON.parse(wardrobeData);
          // 随机选上衣
          const tops = clothes.filter(item => item.category === '上衣');
          if (tops.length > 0) {
            const randomTop = tops[Math.floor(Math.random() * tops.length)];
            this.selectedTopImage = randomTop.image;
          }
          // 随机选裙裤
          const pantsSkirts = clothes.filter(item => item.category === '裙裤');
          if (pantsSkirts.length > 0) {
            const randomBottom = pantsSkirts[Math.floor(Math.random() * pantsSkirts.length)];
            this.selectedBottomImage = randomBottom.image;
          }
        }
      } catch (e) {
        console.error('获取衣橱数据失败', e);
      }
      this.hasInitializedImages = true;
    }
    
    // 接收微信小程序跳转参数
    const appOptions = uni.getLaunchOptionsSync();
    console.log('小程序启动参数:', JSON.stringify(appOptions));
    
    // 检查是否有小程序跳转的参数
    if (appOptions && appOptions.referrerInfo && appOptions.referrerInfo.extraData) {
      console.log('检测到小程序跳转参数:', JSON.stringify(appOptions.referrerInfo.extraData));
      const extraData = appOptions.referrerInfo.extraData;
      
      // 保存用户信息
      if (extraData.token) {
        this.userInfo.token = extraData.token;
        uni.setStorageSync('token', extraData.token);
        console.log('已保存token:', extraData.token);
      }
      
      if (extraData.avatar) {
        this.userInfo.avatar = extraData.avatar;
        uni.setStorageSync('avatar', extraData.avatar);
        console.log('已保存avatar:', extraData.avatar);
      }
      
      if (extraData.nickname) {
        this.userInfo.nickname = extraData.nickname;
        uni.setStorageSync('nickname', extraData.nickname);
        console.log('已保存nickname:', extraData.nickname);
      }
      
      if (extraData.userId) {
        this.userInfo.userId = extraData.userId;
        uni.setStorageSync('userId', extraData.userId);
        console.log('已保存userId:', extraData.userId);
      }
      
      // 处理用户登录状态
      if (extraData.token) {
        Cache.set(LOGIN_STATUS, true);
        console.log('用户已登录，设置登录状态为true');
      }
    }
    
    // 确保有默认的推荐商品数据
    this.setDefaultRecommendations();
    
    // 打印当前页面路由参数
    try {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const options = currentPage.options || currentPage.$page?.options || {};
      console.log('当前路由参数:', JSON.stringify(options));
      
      // 如果路由参数中直接有数据，优先使用路由参数
      if (options && Object.keys(options).length > 0) {
        console.log('从路由获取到参数:', options);
        
        // 设置显示模式和图片
        if (options.fromWardrobe === 'true') {
          this.showFortuneModules = false;
          console.log('从个人衣橱进入，隐藏运势相关模块');
        } else if (options.showFortuneModules === 'true') {
          this.showFortuneModules = true;
          console.log('从时空衣橱表单页面进入，显示运势相关模块');
        }
        
        // 处理从衣橱页面传入的已选衣物
        if (options.selectedTopImage) {
          this.selectedTopImage = decodeURIComponent(options.selectedTopImage);
          console.log('从路由参数获取上衣图片:', this.selectedTopImage);
        }
        
        if (options.selectedBottomImage) {
          this.selectedBottomImage = decodeURIComponent(options.selectedBottomImage);
          console.log('从路由参数获取下装图片:', this.selectedBottomImage);
        }
        
        // 处理模特图片
        if (options.modelImage) {
          // 确保URL是完整的URL（包含http或https前缀）
          let imageUrl = decodeURIComponent(options.modelImage);
          console.log('从路由参数获取模特图片:', imageUrl);
          
          // 确保URL以http开头
          if (imageUrl && imageUrl.indexOf('http') !== 0 && imageUrl.indexOf('//') !== 0) {
            // 尝试使用相对路径或完整路径
            if (getApp().globalData.HTTP_REQUEST_URL) {
              imageUrl = getApp().globalData.HTTP_REQUEST_URL + '/' + imageUrl.replace(/^\/+/, '');
              console.log('已构建完整URL:', imageUrl);
            } else {
              // 如果不是以http或//开头，使用默认图片代替
              console.log('URL格式不正确，使用默认图片');
              imageUrl = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1760598171/p812706.png';
            }
          }
          
          this.personImage = imageUrl;
          console.log('设置模特图片URL:', this.personImage);
          this.shouldAnimateModel = true; // 启用模特动画
        }
        
        // 设置模型参数
        this.modelParams = {
          modelImage: options.modelImage ? decodeURIComponent(options.modelImage) : '',
          birthDate: options.birthDate || '',
          birthTime: options.birthTime || '',
          location: options.location || '',
          tripDate: options.tripDate || '',
          tripTime: options.tripTime || '',
          style: options.style || '',
          tags: options.tags || ''
        };
        
        console.log('设置模型参数:', this.modelParams);
        
        // 处理Coze API返回的数据
        if (options.cozeData) {
          console.log('从路由参数获取cozeData');
          try {
            // 使用自定义解码方法解码数据
            function customDecode(str) {
              try {
                return decodeURIComponent(
                  str
                    .replace(/_p_/g, '%')
                    .replace(/_a_/g, '+')
                    .replace(/_s_/g, '/')
                    .replace(/_e_/g, '=')
                );
              } catch (e) {
                console.error('解码数据时出错:', e);
                return str; // 返回原字符串
              }
            }
            
            const decodedData = customDecode(options.cozeData);
            console.log('解码后的数据长度:', decodedData.length);
            
            // 尝试解析JSON
            let cozeData = JSON.parse(decodedData);
            console.log('成功解析Coze数据');
            
            // 更新界面显示
            if (cozeData.fortune_analysis && typeof cozeData.fortune_analysis.description === 'string') {
              this.analysisText = cozeData.fortune_analysis.description;
              console.log('命理解析:', this.analysisText.substring(0, 50) + '...');
            }
            
            if (cozeData.luck_info && typeof cozeData.luck_info.description === 'string') {
              this.luckDescription = cozeData.luck_info.description;
              console.log('运势描述:', this.luckDescription.substring(0, 50) + '...');
            }
            
            // 设置适合标签
            if (cozeData.fortune_analysis && Array.isArray(cozeData.fortune_analysis.suitable)) {
              this.suitableTags = cozeData.fortune_analysis.suitable;
              console.log('适合标签:', this.suitableTags);
            }
            
            // 设置不适合标签
            if (cozeData.fortune_analysis && Array.isArray(cozeData.fortune_analysis.not_suitable)) {
              this.notSuitableTags = cozeData.fortune_analysis.not_suitable;
              console.log('不适合标签:', this.notSuitableTags);
            }
            
            // 处理推荐商品
            if (cozeData.recommendations && Array.isArray(cozeData.recommendations)) {
              // 更新推荐商品列表
              if (cozeData.recommendations.length > 0) {
                this.recommendItems = cozeData.recommendations;
                console.log('设置推荐商品:', JSON.stringify(this.recommendItems));
              } else {
                console.log('API返回的推荐商品列表为空，使用默认推荐');
                this.setDefaultRecommendations();
              }
              console.log('推荐商品数量:', cozeData.recommendations.length);
            } else {
              console.log('API返回数据中没有recommendations字段，使用默认推荐');
              this.setDefaultRecommendations();
            }
          } catch (jsonError) {
            console.error('解析JSON数据出错:', jsonError);
            // 设置默认值
            this.setDefaultFortuneData();
            this.setDefaultRecommendations();
          }
        }
      } else {
        // 若无路由参数，尝试从本地存储获取
        console.log('路由参数为空，尝试从本地存储获取');
      }
    } catch (e) {
      console.error('获取路由参数失败:', e);
    }
    
    // 检查是否有来自本地存储的参数
    try {
      const wardrobeParams = uni.getStorageSync('wardrobe_params');
      if (wardrobeParams) {
        console.log('检测到个人衣橱参数');
        const params = JSON.parse(wardrobeParams);
        
        // 设置显示模式和图片
        this.showFortuneModules = false;
        console.log('从个人衣橱进入，隐藏运势相关模块');
        
        // 处理从衣橱页面传入的已选衣物
        if (params.selectedTopImage) {
          this.selectedTopImage = params.selectedTopImage;
          console.log('从衣橱页面传入上衣图片:', this.selectedTopImage);
        }
        
        if (params.selectedBottomImage) {
          this.selectedBottomImage = params.selectedBottomImage;
          console.log('从衣橱页面传入下装图片:', this.selectedBottomImage);
        }
        
        // 使用过后清除本地存储的参数
        uni.removeStorageSync('wardrobe_params');
      }
      
      // 检查是否有来自try_on_detail的参数
      const detailParams = uni.getStorageSync('try_on_detail_params');
      if (detailParams) {
        console.log('检测到try_on_detail参数');
        const params = JSON.parse(detailParams);
        
        // 设置相关参数
        this.showFortuneModules = true;
        console.log('从时空衣橱表单页面进入，显示运势相关模块');
        
        // 设置模型参数
        this.modelParams = {
          modelImage: params.modelImage || '',
          birthDate: params.birthDate || '',
          birthTime: params.birthTime || '',
          location: params.location || '',
          tripDate: params.tripDate || '',
          tripTime: params.tripTime || '',
          style: params.style || '',
          tags: params.tags || ''
        };
        
        console.log('接收到的参数:', this.modelParams);
        
        // 如果有模特图片URL，则设置到personImage
        if (this.modelParams.modelImage) {
          // 确保URL是完整的URL（包含http或https前缀）
          let imageUrl = this.modelParams.modelImage;
          
          // 检查URL是否包含编码字符，尝试解码
          if (imageUrl && imageUrl.includes('%')) {
            try {
              imageUrl = decodeURIComponent(imageUrl);
              console.log('已解码URL:', imageUrl);
            } catch (e) {
              console.error('URL解码失败:', e);
            }
          }
          
          // 确保URL以http开头
          if (imageUrl && imageUrl.indexOf('http') !== 0 && imageUrl.indexOf('//') !== 0) {
            // 尝试使用相对路径或完整路径
            if (getApp().globalData.HTTP_REQUEST_URL) {
              imageUrl = getApp().globalData.HTTP_REQUEST_URL + '/' + imageUrl.replace(/^\/+/, '');
              console.log('已构建完整URL:', imageUrl);
            } else {
              // 如果不是以http或//开头，使用默认图片代替
              console.log('URL格式不正确，使用默认图片');
              imageUrl = 'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1760598171/p812706.png';
            }
          }
          
          this.personImage = imageUrl;
          console.log('设置模特图片URL:', this.personImage);
          this.shouldAnimateModel = true; // 启用模特动画
        }
        
        // 处理Coze API返回的数据
        if (params.cozeData) {
          try {
            console.log('开始解析cozeData参数');
            
            // 使用自定义解码方法解码数据
            function customDecode(str) {
              try {
                return decodeURIComponent(
                  str
                    .replace(/_p_/g, '%')
                    .replace(/_a_/g, '+')
                    .replace(/_s_/g, '/')
                    .replace(/_e_/g, '=')
                );
              } catch (e) {
                console.error('解码数据时出错:', e);
                return str; // 返回原字符串
              }
            }
            
            const decodedData = customDecode(params.cozeData);
            console.log('解码后的数据长度:', decodedData.length);
            
            // 尝试解析JSON
            try {
              let cozeData = JSON.parse(decodedData);
              console.log('解析Coze数据成功');
              
              // 更新界面显示
              if (cozeData.fortune_analysis && typeof cozeData.fortune_analysis.description === 'string') {
                this.analysisText = cozeData.fortune_analysis.description;
                console.log('命理解析:', this.analysisText.substring(0, 50) + '...');
              } else {
                console.warn('没有找到有效的fortune_analysis.description');
              }
              
              if (cozeData.luck_info && typeof cozeData.luck_info.description === 'string') {
                this.luckDescription = cozeData.luck_info.description;
                console.log('运势描述:', this.luckDescription.substring(0, 50) + '...');
              } else {
                console.warn('没有找到有效的luck_info.description');
              }
              
              // 设置适合标签
              if (Array.isArray(cozeData.fortune_analysis.suitable)) {
                this.suitableTags = cozeData.fortune_analysis.suitable;
                console.log('适合标签:', this.suitableTags);
              }
              
              // 设置不适合标签
              if (Array.isArray(cozeData.fortune_analysis.not_suitable)) {
                this.notSuitableTags = cozeData.fortune_analysis.not_suitable;
                console.log('不适合标签:', this.notSuitableTags);
              }
            } catch (jsonError) {
              console.error('解析JSON数据出错:', jsonError);
              // 设置默认值
              this.setDefaultFortuneData();
              this.setDefaultRecommendations();
            }
          } catch (e) {
            console.error('处理Coze数据总体出错:', e);
            // 设置默认值
            this.setDefaultFortuneData();
            this.setDefaultRecommendations();
          }
        }
        
        // 使用过后清除本地存储的参数
        uni.removeStorageSync('try_on_detail_params');
      }
    } catch (e) {
      console.error('读取本地存储参数失败:', e);
    }
    
    // 修改动画逻辑，不管从哪里进来都有动画效果
    setTimeout(() => {
      this.zoomAnimation = true;
      
      // 1.5秒后开始打字机动画
      setTimeout(() => {
        this.startTypingAnimations();
        
        // 动画完成后恢复正常大小
        setTimeout(() => {
          this.zoomAnimation = false;
        }, 2500);
      }, 1500);
    }, 500);
  },
}
</script>

<style lang="scss" scoped>
// 主容器
.recommendation-container {
  display: flex;
  flex-direction: column;
  // 改回高级感渐变浅粉色背景
  background: linear-gradient(150deg, #fff9fb, #ffecf3, #fedfeb);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  min-height: 100vh;
  position: relative; // 确保定位上下文
  
  // 从衣橱进入时的样式
  &.from-wardrobe {
    background: linear-gradient(150deg, #f8f9ff, #e6f0ff, #e0ebff);
  }
}

// 顶部区域，包含状态栏和导航栏
.header-area {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: linear-gradient(120deg, #ff5b9a 60%, #a85ce0 100%);
  box-shadow: 0 4px 24px 0 rgba(255,107,157,0.08);
  /* 去除圆角和遮罩 */
}

// 顶部状态栏
.status-bar {
  width: 100%;
}

// 导航栏
.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  height: 50px; // 明确设置导航栏高度
  
  .back-btn {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .back-icon {
      width: 22px;
      height: 22px;
      opacity: 0.9; // 更微妙的透明度
    }
  }
  
  .page-title {
    color: #fff;
    font-size: 18px;
    font-weight: 600; // 减轻粗体
    letter-spacing: 1px; // 增加字间距
  }
  
  .placeholder-btn {
    width: 40px;
    height: 40px;
  }
}

// 内容区域
.content-area {
  background: #faf7fa;
  /* 去除顶部圆角 */
  margin-top: 0;
  min-height: 100vh;
  box-shadow: 0 -2px 16px 0 rgba(255,107,157,0.04);
  padding-bottom: 30px;
}

// 试穿预览区
.preview-section {
  background-color: #fff;
  margin: 0;
  padding: 0;
  border-radius: 0;
  box-shadow: none;

  .image-comparison {
    display: flex;
    justify-content: space-between;
    margin: 15px;
    height: 320px; // 增加高度

    .left-column {
      width: 48%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      
      .image-placeholder {
        width: 100%;
        height: 48%;
        border: none; // 移除边框
        border-radius: 12px; // 增加圆角
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #fff; // 纯白背景
        overflow: hidden;
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15); // 加深阴影
        
        &.upper {
          margin-bottom: 5px;
        }
        
        &.lower {
          margin-top: 5px;
        }
        
        .placeholder-text {
          color: #999; // 更柔和的颜色
          font-size: 16px;
          font-weight: 500; // 减轻粗体
        }
        
        .preview-image {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
    }
    
    .right-column {
      width: 48%;
      height: 100%;
      transform-origin: center;
      transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
      
      .image-placeholder {
        width: 100%;
        height: 100%;
        border: none; // 移除边框
        border-radius: 12px; // 增加圆角
        display: flex;
        justify-content: center;
        align-items: center;
        background: linear-gradient(145deg, #fff, #f8f8f8); // 微妙渐变背景
        overflow: hidden;
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.18); // 加深模特展示区阴影
        
        .placeholder-text {
          color: #999; // 更柔和的颜色
          font-size: 16px;
          font-weight: 500; // 减轻粗体
        }
        
        .preview-image {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
    }
  }

  .try-on-button {
    width: 200px; /* 更宽更大气 */
    height: 48px; /* 更高更显眼 */
    margin: 0 auto 24px auto; /* 居中并加大底部间距 */
    padding: 0;
    font-size: 20px; /* 字体更大 */
    border-radius: 26px; /* 圆角更大 */
    box-shadow: 0 8px 24px rgba(255, 51, 102, 0.18), 0 2px 8px rgba(255,255,255,0.12); /* 阴影更柔和有层次 */
    letter-spacing: 2.5px;
    font-weight: 700; /* 更粗 */
    background: linear-gradient(90deg, #ff5b9a 0%, #ff3366 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.18s cubic-bezier(0.4,0,0.2,1);
    color: #fff; /* 按钮文本为白色 */
    border: none;
    position: relative;
    overflow: hidden;
  }
  .try-on-button .button-content {
    font-size: 20px; /* 字体更大 */
    font-weight: 700;
    letter-spacing: 2.5px;
    color: #fff; /* 文本为白色 */
    text-shadow: 0 2px 8px rgba(255,51,102,0.08); /* 增加轻微文字阴影提升高级感 */
  }
  .try-on-button .button-icon {
    margin-right: 12px;
  }
  .try-on-button:active:not(.button-disabled) {
    transform: translateY(2px);
    box-shadow: 0 3px 8px rgba(255, 255, 255, 0.3); /* 保持点击阴影 */
  }
  .try-on-button::after { /* 新增高光渐变提升质感 */
    content: '';
    position: absolute;
    left: 0; top: 0; right: 0; bottom: 0;
    border-radius: 26px;
    background: linear-gradient(120deg,rgba(255,255,255,0.18) 0%,rgba(255,255,255,0.04) 100%);
    pointer-events: none;
    z-index: 1;
  }

  .try-on-button:active:not(.button-disabled) {
    transform: translateY(2px);
    box-shadow: 0 3px 8px rgba(255, 255, 255, 0.3);
  }

  &.button-disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  display: block;
}

.analysis-section {
  background-color: #fff;
  margin: 0;
  padding: 20px 15px; // 增加垂直内边距
  border-radius: 0;
  box-shadow: none;
  
  .section-title {
    font-size: 16px;
    font-weight: 600; // 减轻粗体
    margin-bottom: 12px;
    color: #333;
    letter-spacing: 0.5px; // 增加字间距
  }

  .analysis-text {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
    margin-bottom: 18px;
    letter-spacing: 0.2px; // 更好的可读性
  }

  .analysis-tags-row {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .tag-label {
      font-size: 15px;
      color: #222222;
      margin-right: 20px;  /* 右侧间距 */
      margin-top: 30px;    /* 新增：上方留白 */
      white-space: nowrap;
      font-weight: 600;
      background-color: #64646425;
      border-radius: 8px;
      min-width: 60px;
      text-align: center;
      padding: 4px 8px;    /* 可选：增加内边距让文字更舒适 */
      box-sizing: border-box;  /* 确保 padding 不影响总宽度 */
    }
    .tag-label2 {
      font-size: 15px;
      color: #222222;
      margin-right: 20px;  /* 右侧间距 */
      white-space: nowrap;
      font-weight: 600;
      background-color: #64646425;
      border-radius: 8px;
      min-width: 60px;
      text-align: center;
      padding: 4px 8px;    /* 可选：增加内边距让文字更舒适 */
      box-sizing: border-box;  /* 确保 padding 不影响总宽度 */
    }

    .tags-group {
      display: flex;
      flex-wrap: wrap;
      gap: 12px; // 增加标签之间的间距
    }

    .tag {
      font-size: 12px;
      color: #666;
      padding: 5px 12px; // 增加内部填充
      border-radius: 15px;
      background-color: #f5f5f5; // 更轻的背景色

      &.highlight {
        color: #fff;
        background-color: #ff5b9a; // 今日宜高亮
         margin-top: 30px;    /* 新增：上方留白 */
        font-weight: normal;

      &.highlight2 {
        color: #fff;
        background-color: #000000; // 今日忌高亮
        font-weight: normal;
      }
      }
    }
  }
}

.fortune-section {
  background-color: #fff;
  margin: 0;
  padding: 20px 15px; // 增加垂直内边距
  border-radius: 0;
  box-shadow: none;
  border-top: 1px solid #f0f0f0;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 18px;
    color: #333;
    letter-spacing: 0.5px;
  }

  .fortune-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 14px;
    font-size: 14px;

    .star-rating {
      width: 65%; // 增加宽度
      position: relative;
      height: 20px; // 增加高度

      .rating-bar {
        height: 5px; // 稍微加粗
        position: absolute;
        bottom: 0;
        left: 0;
        border-radius: 2.5px; // 圆角匹配高度

        &.pink {
          background: linear-gradient(90deg, #ff3366, #ff6699); // 添加渐变
        }

        &.purple {
          background: linear-gradient(90deg, #9c27b0, #ba68c8); // 添加渐变
        }

        &.blue {
          background: linear-gradient(90deg, #2196f3, #64b5f6); // 添加渐变
        }
      }

      .stars-text {
        position: absolute;
        top: -5px;
        left: 0;
        width: 100%;
        text-align: left;
        font-size: 14px;
        color: #ff5b9a; // 匹配主题色
        letter-spacing: 1px; // 星星间距
      }
    }
  }
}

// 推荐商品部分
.recommendation-list-section {
  background: #fff;
  border-radius: 18px 18px 12px 12px;
  margin: 20px 10px 18px 10px; /* 顶部间距加大为20px */
  box-shadow: 0 2px 12px 0 rgba(255,107,157,0.06);
  padding-top: 10px;
  padding-bottom: 8px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 18px;
    padding: 0 6px 2px 6px;
    border-bottom: 1.5px solid #f6f6f6;
    background: #fff;
  }
  .section-title {
    font-size: 18px;
    font-weight: 700;
    color: #222;
    letter-spacing: 1px;
    margin-bottom: 0;
  }
  .view-all {
    font-size: 12px;
    color: #888;
    padding: 2px 12px;
    border-radius: 14px;
    background: #f7f7f7;
    border: 1px solid #ececec;
    transition: background 0.2s, color 0.2s;
    margin-left: 10px;
  }
  .view-all:active {
    background: #ececec;
    color: #ff3366;
  }

  .recommendation-item {
    display: flex;
    margin-bottom: 18px;
    padding-bottom: 18px;
    border-bottom: 1px solid #f0f0f0; // 更淡的分隔线

    &:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }

    // 图片占位符
    .item-image-placeholder {
      width: 80px;
      height: 100px;
      border-radius: 8px; // 更大的圆角
      margin-right: 15px;
      flex-shrink: 0;
      background-color: #fafafa;
      border: 1px dashed rgba(0, 0, 0, 0.1);
      display: flex;
      justify-content: center;
      align-items: center;
      color: #999;
      font-size: 12px;
      overflow: hidden; // 确保图片不会溢出容器
      
      .item-image {
        width: 100%;
        height: 100%;
        object-fit: cover; // 图片填充容器
      }
    }

    .item-details {
      flex-grow: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .item-name {
        font-size: 14px;
        font-weight: 600;
        margin-bottom: 4px;
        color: #333; // 更深的文字颜色
      }

      .item-description {
        font-size: 12px;
        color: #666;
        margin-bottom: 10px;
        line-height: 1.5;
      }

      .item-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;

        .tag {
          font-size: 10px;
          padding: 2px 8px;
          border-radius: 10px;
          border: none; // 移除边框
          background-color: #f5f5f5; // 统一背景色
          color: #666; // 统一文字颜色

          &.recommended {
            color: #ff3366;
            background-color: rgba(255, 51, 102, 0.1); // 半透明背景
          }
          &.hot {
            color: #ff5722;
            background-color: rgba(255, 87, 34, 0.1);
          }
          &.style {
            color: #4caf50;
            background-color: rgba(76, 175, 80, 0.1);
          }
          &.new {
            color: #2196f3;
            background-color: rgba(33, 150, 243, 0.1);
          }
          &.luck {
            color: #ff9800;
            background-color: rgba(255, 152, 0, 0.1);
          }
          &.discount {
            color: #9c27b0;
            background-color: rgba(156, 39, 176, 0.1);
          }
        }
      }
    }

    .item-action {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      justify-content: space-between;
      margin-left: 10px;
      flex-shrink: 0;

      .item-price {
        font-size: 15px;
        color: #ff3366;
        font-weight: 600;
        margin-bottom: 12px;
      }

      .add-button {
        padding: 4px 14px;
        background-color: #fff;
        color: #ff3366;
        border: 1px solid #ff3366;
        border-radius: 15px;
        font-size: 12px;
        cursor: pointer;
        line-height: 1.5;
        height: auto;
        min-height: unset;

        &:active {
          background-color: rgba(255, 51, 102, 0.05);
        }

        &::after {
          border: none;
        }
      }
    }
  }
}

.image-placeholder {
  position: relative; // 添加相对定位
  transition: all 0.3s ease;
  
  &.animating {
    animation: imageFlash 1.2s ease; // 增加动画时间
  }
  
  &.generating {
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(
        90deg, 
        rgba(255,255,255,0) 0%, 
        rgba(255,255,255,0.3) 50%, 
        rgba(255,255,255,0) 100%
      );
      animation: shine 1.5s infinite;
      z-index: 2;
    }
  }
  
  &.generated {
    animation: popEffect 0.8s ease; // 增强弹出效果
  }
  
  .model-image {
    opacity: 0.9;
  }
  
  .change-btn {
    position: absolute;
    right: 10px;
    bottom: 10px;
    background: linear-gradient(135deg, rgba(255,91,154,0.8) 0%, rgba(255,51,102,0.9) 100%);
    color: #fff;
    padding: 6px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
    box-shadow: 0 2px 8px rgba(255, 51, 102, 0.3);
    transition: all 0.3s ease;
    z-index: 5;
    backdrop-filter: blur(2px);
    border: 1px solid rgba(255,255,255,0.2);
    
    &:active {
      transform: scale(0.95) translateY(1px);
      background: linear-gradient(135deg, rgba(255,91,154,0.9) 0%, rgba(255,51,102,1) 100%);
      box-shadow: 0 1px 4px rgba(255, 51, 102, 0.3);
    }
    
    &.top-z-index {
      z-index: 10; // 更高的z-index确保在生成图片和动画层之上
      background: rgba(255,51,102,0.9); // 更明显的背景以便于区分
      box-shadow: 0 2px 10px rgba(255, 51, 102, 0.5);
      border: 1px solid rgba(255,255,255,0.4);
    }
  }
  
  .generating-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255,255,255,0.7);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 3;
    overflow: hidden; // 确保扫描线不超出容器
    
    .scanning-line {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 2px;
      background: linear-gradient(to right, 
        rgba(255,51,102,0) 0%, 
        rgba(255,51,102,0.8) 50%, 
        rgba(255,51,102,0) 100%
      );
      box-shadow: 0 0 8px rgba(255,51,102,0.5);
      animation: scanning 1.5s linear infinite;
      z-index: 4;
    }
    
    .generating-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid rgba(255,51,102,0.3);
      border-top: 3px solid rgba(255,51,102,1);
      border-radius: 50%;
      margin-bottom: 15px;
      animation: spin 1s linear infinite;
    }
    
    .generating-text {
      color: #ff3366;
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 12px;
    }
    
    .progress-container {
      width: 80%;
      height: 6px;
      background-color: rgba(255, 51, 102, 0.2);
      border-radius: 3px;
      overflow: hidden;
      
      .progress-bar {
        height: 100%;
        background: linear-gradient(to right, #ff3366, #ff5b9a);
        border-radius: 3px;
        transition: width 0.3s ease;
      }
    }
  }
  
  .success-animation {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 4;
    overflow: hidden; // 确保花瓣动画不超出容器
  }
}

// 动画定义
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes shine {
  0% { left: -100%; }
  100% { left: 100%; }
}

@keyframes scaleUp {
  0% { transform: scale(0); opacity: 0.8; }
  80% { transform: scale(1.1); opacity: 0.9; }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes checkmark {
  0% { transform: rotate(45deg) scale(0); opacity: 0; }
  70% { transform: rotate(45deg) scale(1.2); opacity: 1; }
  100% { transform: rotate(45deg) scale(1); opacity: 1; }
}

@keyframes popEffect {
  0% { transform: scale(0.9); opacity: 0.5; }
  50% { transform: scale(1.15); opacity: 1; } // 增加缩放比例
  75% { transform: scale(0.95); opacity: 1; }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes imageFlash {
  0% { transform: scale(1); filter: brightness(1); }
  40% { transform: scale(1.15); filter: brightness(1.2); } // 增加缩放比例
  60% { transform: scale(1.15); filter: brightness(1.2); } // 保持缩放状态更长时间
  100% { transform: scale(1); filter: brightness(1); }
}

// 添加新的闪光效果
@keyframes glow {
  0% { box-shadow: 0 0 5px rgba(255, 51, 102, 0.5); }
  50% { box-shadow: 0 0 20px rgba(255, 51, 102, 0.8); }
  100% { box-shadow: 0 0 5px rgba(255, 51, 102, 0.5); }
}

// 添加扩散效果
.success-animation {
  .success-ripple {
    position: absolute;
    border: 2px solid rgba(76, 175, 80, 0.5);
    border-radius: 50%;
    animation: ripple 1s ease-out forwards;
    opacity: 1;
  }
}

@keyframes ripple {
  0% { 
    width: 0; 
    height: 0; 
    opacity: 1; 
  }
  100% { 
    width: 200px; 
    height: 200px; 
    opacity: 0; 
    margin-left: -100px;
    margin-top: -100px;
  }
}

// 添加扫描动画
@keyframes scanning {
  0% { transform: translateY(0); opacity: 0.8; }
  50% { opacity: 1; }
  100% { transform: translateY(100vh); opacity: 0.8; }
}

// 添加模特动画样式
.model-area.animate-model {
  animation: modelEnterAnimation 1.2s ease-out forwards;
}

@keyframes modelEnterAnimation {
  0% {
    opacity: 0;
    transform: scale(0.8);
  }
  70% {
    opacity: 1;
    transform: scale(1.1);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

// 打字机文本样式
.luck-description, .analysis-text {
  min-height: 1.5em; // 确保高度一致，避免打字时抖动
}

// 添加缩放后恢复的动画
@keyframes zoom-and-revert {
  0% { transform: scale(1); }
  40% { transform: scale(1.15); }
  80% { transform: scale(1.15); }
  100% { transform: scale(1); }
}
</style> 